#!/usr/bin/env python3
#
# make-reg.py
# Registration Macros Generator
#
# Copyright 2022 by Moshe Kaplan
# Based on make-reg.pl by Luis E. Garcia Onatnon <luis.ontanon@gmail.com>
#
# Wireshark - Network traffic analyzer
# By Gerald Combs <gerald@wireshark.org>
# Copyright 1998 Gerald Combs
#
# SPDX-License-Identifier: GPL-2.0-or-later

import argparse
import re


def parse_file(file_content):
    # extract classes, functions, and internal functions
    # and return them as a tuple
    CLASS_PATTERN = r'WSLUA_CLASS_DEFINE(?:_BASE)?\050\s*([A-Za-z0-9]+)'
    FUNCTION_PATTERN = r'WSLUA_FUNCTION\s+wslua_([a-z_0-9]+)'
    INTERNAL_FUNCTION_PATTERN = r'WSLUA_INTERNAL_FUNCTION\s+wslua_([a-z_0-9]+)'

    class_matches = re.findall(CLASS_PATTERN, file_content)
    function_matches = re.findall(FUNCTION_PATTERN, file_content)
    internal_function_matches = re.findall(INTERNAL_FUNCTION_PATTERN, file_content)
    return class_matches, function_matches, internal_function_matches


def generate_declare_wslua_h(classes, functions, internal_functions):
    output_lines = []
    output_lines += ["/* This file is automatically generated by make-reg.py; do not edit! */\n"]
    output_lines += ["#define WSLUA_DECLARE_CLASSES() \\"]
    for lua_class in classes:
        output_lines += ["\tWSLUA_CLASS_DECLARE({lua_class});\\".format(lua_class=lua_class)]

    output_lines += ["\n"]
    output_lines += ["#define WSLUA_DECLARE_FUNCTIONS() \\"]
    for lua_function in functions:
        output_lines += ["\tWSLUA_FUNCTION wslua_{lua_function}(lua_State* L);\\".format(lua_function=lua_function)]

    for lua_internal_function in internal_functions:
        output_lines += ["\tWSLUA_INTERNAL_FUNCTION wslua_{lua_internal_function}(lua_State* L);\\".format(lua_internal_function=lua_internal_function)]

    output_lines += ["\n"]
    output_lines += ["extern void wslua_register_classes(lua_State* L);"]
    output_lines += ["extern void wslua_register_functions(lua_State* L);"]
    output_lines += ["\n\n"]
    return "\n".join(output_lines)


def generate_register_wslua_c(classes, functions, internal_functions):
    output_lines = []
    output_lines += ["/* This file is automatically generated by make-reg.py; do not edit! */\n"]
    output_lines += ['#include "config.h"']
    output_lines += ['#include "wslua.h"\n']
    output_lines += ['#include "lua_bitop.h"\n']
    output_lines += ["static void wslua_reg_module(lua_State* L, const char *name _U_, lua_CFunction func) {"]
    output_lines += ["\tlua_pushcfunction(L, func);"]
    output_lines += ["\tlua_call(L, 0, 0);"]
    output_lines += ["}\n"]
    output_lines += ["void wslua_register_classes(lua_State* L) {"]
    for lua_class in classes:
        output_lines += ["\twslua_reg_module(L, \"{lua_class}\", {lua_class}_register);".format(lua_class=lua_class)]

    output_lines += ["\twslua_reg_module(L, \"bit\", luaopen_bit);"]
    output_lines += ["\tlua_pushcfunction(L, luaopen_rex_pcre2);"]
    output_lines += ["\tlua_call(L, 0, 1);"]
    output_lines += ["\tlua_setglobal(L, \"rex_pcre2\");"]
    output_lines += ["}\n"]

    output_lines += ["void wslua_register_functions(lua_State* L) {"]
    for lua_function in functions:
        output_lines += ["\tWSLUA_REGISTER_FUNCTION({lua_function});".format(lua_function=lua_function)]

    for lua_internal_function in internal_functions:
        output_lines += ["\tWSLUA_REGISTER_FUNCTION({lua_internal_function});".format(lua_internal_function=lua_internal_function)]

    output_lines += ["}\n"]

    return "\n".join(output_lines)


def main():
    parser = argparse.ArgumentParser(description="Generate the registration macros for Lua code.")
    parser.add_argument("files", metavar='files', nargs='+', help="paths to Lua C code")
    parsed_args = parser.parse_args()

    lua_classes = []
    lua_functions = []
    lua_internal_functions = []
    for filename in parsed_args.files:
        with open(filename, encoding='utf-8') as fh:
            class_matches, function_matches, internal_function_matches = parse_file(fh.read())
        lua_classes += class_matches
        lua_functions += function_matches
        lua_internal_functions += internal_function_matches

    declare_wslua_h_content = generate_declare_wslua_h(lua_classes, lua_functions, lua_internal_functions)
    register_wslua_c_content = generate_register_wslua_c(lua_classes, lua_functions, lua_internal_functions)

    with open('register_wslua.c', mode='w', encoding='utf-8') as fh:
        fh.write(register_wslua_c_content)

    with open('declare_wslua.h', mode='w', encoding='utf-8') as fh:
        fh.write(declare_wslua_h_content)


if __name__ == '__main__':
    main()
